"""
Django settings for website project.
"""

from pathlib import Path
import os

# Build paths inside the project like this: BASE_DIR / 'subdir'.
BASE_DIR = Path(__file__).resolve().parent.parent

# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = 'django-insecure-your-secret-key'

# SECURITY WARNING: don't run with debug turned on in production!
DEBUG = os.environ.get('DEBUG', 'True') == 'True'

ALLOWED_HOSTS = ['*']

# Application definition
INSTALLED_APPS = [
    'simpleui',  # admin美化
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
    'rest_framework',  # DRF框架
    'import_export',  # 数据导入导出
    'corsheaders',  # 跨域支持
    'navigation',  # 导航应用
]

MIDDLEWARE = [
    'django.middleware.security.SecurityMiddleware',
    'django.contrib.sessions.middleware.SessionMiddleware',
    'corsheaders.middleware.CorsMiddleware',  # CORS中间件必须在CommonMiddleware之前
    'django.middleware.common.CommonMiddleware',
    'django.middleware.csrf.CsrfViewMiddleware',
    'django.contrib.auth.middleware.AuthenticationMiddleware',
    'django.contrib.messages.middleware.MessageMiddleware',
    'django.middleware.clickjacking.XFrameOptionsMiddleware',
]

ROOT_URLCONF = 'website.urls'

TEMPLATES = [
    {
        'BACKEND': 'django.template.backends.django.DjangoTemplates',
        'DIRS': [],
        'APP_DIRS': True,
        'OPTIONS': {
            'context_processors': [
                'django.template.context_processors.debug',
                'django.template.context_processors.request',
                'django.contrib.auth.context_processors.auth',
                'django.contrib.messages.context_processors.messages',
            ],
        },
    },
]

WSGI_APPLICATION = 'website.wsgi.application'

# 数据库配置
# 根据环境变量判断使用MySQL还是SQLite
DB_ENGINE = os.environ.get('DB_ENGINE', '')

if DB_ENGINE == 'mysql':
    # 使用MySQL数据库
    DATABASES = {
        'default': {
            'ENGINE': 'django.db.backends.mysql',
            'NAME': os.environ.get('DB_NAME', 'nav'),
            'USER': os.environ.get('DB_USER', 'root'),
            'PASSWORD': os.environ.get('DB_PASSWORD', ''),
            'HOST': os.environ.get('DB_HOST', 'localhost'),
            'PORT': os.environ.get('DB_PORT', '3306'),
            'OPTIONS': {
                'charset': 'utf8mb4',
                'init_command': 'SET sql_mode="STRICT_TRANS_TABLES"'
            }
        }
    }
else:
    # 默认使用SQLite数据库
    DATABASES = {
        'default': {
            'ENGINE': 'django.db.backends.sqlite3',
            'NAME': BASE_DIR / 'db.sqlite3',
        }
    }

# 密码验证
AUTH_PASSWORD_VALIDATORS = [
    {
        'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator',
    },
    {
        'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator',
    },
    {
        'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator',
    },
    {
        'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator',
    },
]

# 国际化
LANGUAGE_CODE = 'zh-hans'
TIME_ZONE = 'Asia/Shanghai'
USE_I18N = True
USE_TZ = True

# Static files (CSS, JavaScript, Images)
# https://docs.djangoproject.com/en/5.0/howto/static-files/

STATIC_URL = '/static/'
STATIC_ROOT = os.path.join(BASE_DIR, 'staticfiles')
STATICFILES_DIRS = [
    os.path.join(BASE_DIR, 'navigation/static'),  # 统一使用 navigation/static 目录
]

# 不再需要Media配置，因为图片以base64格式存储在数据库中
# MEDIA_URL = '/media/'
# MEDIA_ROOT = os.path.join(BASE_DIR, 'media')

# 默认主键类型
DEFAULT_AUTO_FIELD = 'django.db.models.BigAutoField'

# SimpleUI 配置
SIMPLEUI_DEFAULT_THEME = 'admin.lte.css'
SIMPLEUI_HOME_TITLE = '导航站点管理'
SIMPLEUI_LOGO = 'https://www.django-rest-framework.org/img/logo.png'

# 隐藏用户组和其他不需要的模块
SIMPLEUI_CONFIG = {
    'system_keep': False,  # 不保留系统默认展示
    'menu_display': ['导航站点', '认证和授权'],  # 只显示这些应用
    'dynamic': False,  # 关闭动态菜单
    'menus': [
        {
            'name': '导航站点',
            'icon': 'fas fa-compass',
            'models': [
                {
                    'name': '导航分组',
                    'icon': 'fas fa-folder',
                    'url': 'navigation/navigationgroup/'
                },
                {
                    'name': '导航链接',
                    'icon': 'fas fa-link',
                    'url': 'navigation/navigationlink/'
                }
            ]
        },
        {
            'name': '认证和授权',
            'icon': 'fas fa-user-shield',
            'models': [
                {
                    'name': '用户',
                    'icon': 'fas fa-user',
                    'url': 'auth/user/'
                }
            ]
        }
    ]
}

# CSRF 跨域信任域名配置（支持环境变量动态追加）
CSRF_TRUSTED_ORIGINS = [
    "http://127.0.0.1:8000",
    "https://127.0.0.1:8000",
    "http://localhost:8000",
    "https://localhost:8000",
    "http://localhost",
    "https://localhost",
    "http://127.0.0.1",
    "https://127.0.0.1",
]
# 通过环境变量追加信任域名，多个用逗号分隔
_extra_origins = os.environ.get('CSRF_TRUSTED_EXTRA_ORIGINS', '')
if _extra_origins:
    CSRF_TRUSTED_ORIGINS += [x.strip() for x in _extra_origins.split(',') if x.strip()]
del _extra_origins

# CORS 允许跨域白名单
CORS_ORIGIN_WHITELIST = [
    "http://127.0.0.1:8000",
    "http://localhost:8000",
    "http://localhost",
    "http://127.0.0.1",
]

# 为了更灵活处理CSRF，可以使用较宽松的设置
CSRF_COOKIE_SAMESITE = 'Lax'  # 默认为'Lax'，可设为'None'以允许跨站访问

# CORS配置
CORS_ALLOW_ALL_ORIGINS = True  # 允许所有来源的跨域请求
CORS_ALLOW_CREDENTIALS = True  # 允许跨域请求携带认证信息（cookies）
CORS_ALLOW_METHODS = [
    'DELETE',
    'GET',
    'OPTIONS',
    'PATCH',
    'POST',
    'PUT',
]
CORS_ALLOW_HEADERS = [
    'accept',
    'accept-encoding',
    'authorization',
    'content-type',
    'dnt',
    'origin',
    'user-agent',
    'x-csrftoken',
    'x-requested-with',
]

# DRF配置
REST_FRAMEWORK = {
    'DEFAULT_PERMISSION_CLASSES': [
        'rest_framework.permissions.DjangoModelPermissionsOrAnonReadOnly'
    ],
    'DEFAULT_PAGINATION_CLASS': 'rest_framework.pagination.PageNumberPagination',
    'PAGE_SIZE': 10
}

# 导入导出配置
IMPORT_EXPORT_USE_TRANSACTIONS = True
